package com.youaishujuhui.devops.web.controller.db;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.nutz.dao.Cnd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.WebSocketSession;

import com.youaishujuhui.devops.web.cache.GlobalCache;
import com.youaishujuhui.devops.web.domain.db.AppGamedbBakMsg;
import com.youaishujuhui.devops.web.domain.db.AppInfocenterBakMsg;
import com.youaishujuhui.devops.web.domain.game.Game;
import com.youaishujuhui.devops.web.domain.game.GameProcess;
import com.youaishujuhui.devops.web.domain.host.Host;
import com.youaishujuhui.devops.web.domain.manage.SysUser;
import com.youaishujuhui.devops.web.po.SSHExecResult;
import com.youaishujuhui.devops.web.po.db.GameDbBakItemPO;
import com.youaishujuhui.devops.web.po.db.GameDbBakPO;
import com.youaishujuhui.devops.web.po.db.InfocenterDbBakItemPO;
import com.youaishujuhui.devops.web.po.db.InfocenterDbBakPO;
import com.youaishujuhui.devops.web.service.SSHService;
import com.youaishujuhui.devops.web.service.db.AppGamedbBakMsgService;
import com.youaishujuhui.devops.web.service.db.AppInfocenterBakMsgService;
import com.youaishujuhui.devops.web.service.game.GameProcessService;
import com.youaishujuhui.devops.web.service.game.GameService;
import com.youaishujuhui.devops.web.service.host.HostService;
import com.youaishujuhui.devops.web.util.Common;
import com.youaishujuhui.devops.web.util.db.DbBakRemoteTask;
import com.youaishujuhui.devops.web.util.syslog.SystemLog;
import com.youaishujuhui.devops.web.vo.Result;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;

@Controller
@RequestMapping("/db/bak")
public class DbBakController {
	
	@Autowired
	private GameService gameService;
	
	@Autowired
	private GameProcessService gameProcessService;
	
	@Autowired
	private AppGamedbBakMsgService appGamedbBakMsgService;
	
	@Autowired
	private AppInfocenterBakMsgService appInfocenterBakMsgService;
	
	@Autowired
	private HostService hostService;
	
	@Autowired
	private SSHService sshService;
	
	@RequestMapping(value = "/receiveInfocenterBakMsg", method = RequestMethod.POST)
    @ResponseBody
    public String receiveInfocenterBakMsg(HttpServletRequest request){
		String area_type = getParaElseEmpty(request, "area_type");
		String ctcc_ip = getParaElseEmpty(request, "local_ip");
		//String game_name = getParaElseEmpty(request, "game_name");
		String file_name = getParaElseEmpty(request, "file_name");
		String file_md5 = getParaElseEmpty(request, "file_md5");
		String file_size = getParaElseEmpty(request, "file_size");
		String file_time = getParaElseEmpty(request, "file_time");
		String db_bak_stat = getParaElseEmpty(request, "db_bak_stat");
		
		try {
			Host host = hostService.fetch(Cnd.where("lanIp", "=", ctcc_ip).and("state", "=", Common.HOST_STATE_ONLINE));
			if (host != null) {
				ctcc_ip = host.getCtccIp();
			}
		} catch (Exception e) {
			System.out.println(ctcc_ip + "IP查询出错");
		}

		AppInfocenterBakMsg infoMsg = null;
		try {
			infoMsg = appInfocenterBakMsgService.fetch(Cnd.where("area_type", "=", area_type).and("ctcc_ip", "=", ctcc_ip));
		} catch (Exception e) {
			System.out.println("没有查询到远程中央服数据库备份信息");
		}

		// 是新的备份信息还是旧的备份信息？
		if (infoMsg == null) {
			// 创建数据库备份记录
			infoMsg = new AppInfocenterBakMsg();
			infoMsg.setArea_type(area_type);
			infoMsg.setCtcc_ip(ctcc_ip);
			infoMsg.setFile_name(file_name);
			infoMsg.setFile_md5(file_md5);
			infoMsg.setFile_size(file_size);
			infoMsg.setFile_time(file_time);
			infoMsg.setDb_bak_stat(db_bak_stat);
			
			appInfocenterBakMsgService._insert(infoMsg);
		} else {
			infoMsg.setArea_type(area_type);
			infoMsg.setCtcc_ip(ctcc_ip);
			infoMsg.setFile_name(file_name);
			infoMsg.setFile_md5(file_md5);
			infoMsg.setFile_size(file_size);
			infoMsg.setFile_time(file_time);
			infoMsg.setDb_bak_stat(db_bak_stat);
			
			appInfocenterBakMsgService._update(infoMsg);
		}
	  
		return "Success";
	}
	
    @RequestMapping(value = "/receiveBakMsg", method = RequestMethod.POST)
    @ResponseBody
    public String receiveBakMsg(HttpServletRequest request){
    	String area_type = getParaElseEmpty(request, "area_type");
    	String local_ip = getParaElseEmpty(request, "local_ip");

    	// 把脚本提交的gamedir等参数组成list
        List<String> gamedir_list = new ArrayList<>();
        List<String> server_id_list = new ArrayList<>();
		List<String> gamedb_file_name_lst = new ArrayList<>();
		List<String> gamedb_file_md5_lst = new ArrayList<>();
		List<String> gamedb_file_size_lst = new ArrayList<>();
		List<String> gamedb_file_time_lst = new ArrayList<>();
		List<String> logdb_file_name_lst = new ArrayList<>();
		List<String> logdb_file_md5_lst = new ArrayList<>();
		List<String> logdb_file_size_lst = new ArrayList<>();
		List<String> logdb_file_time_lst = new ArrayList<>();
		List<String> log_db_bak_stat_lst = new ArrayList<>();
		List<String> game_db_bak_stat_lst = new ArrayList<>();
	    
	    int gameserver_count = 0;
	    for (int i = 0; i < 100; ++i) {
	    	String gamedir = "gamedir" + i;
	    	
	    	if (request.getParameterMap().containsKey(gamedir)) {
		    	String server_id = "server_id" + i;
		    	String gamedb_file_name = "gamedb_file_name" + i;
		    	String gamedb_file_md5 = "gamedb_file_md5" + i;
		    	String gamedb_file_size = "gamedb_file_size" + i;
		    	String gamedb_file_time = "gamedb_file_time" + i;
		    	String logdb_file_name = "logdb_file_name" + i;
		    	String logdb_file_md5 = "logdb_file_md5" + i;
		    	String logdb_file_size = "logdb_file_size" + i;
		    	String logdb_file_time = "logdb_file_time" + i;
		    	String log_db_bak_stat = "log_db_bak_stat" + i;
		    	String game_db_bak_stat = "game_db_bak_stat" + i;

		    	gamedir_list.add(getParaElseEmpty(request, gamedir));
	            server_id_list.add(getParaElseEmpty(request, server_id));
	            gamedb_file_name_lst.add(getParaElseEmpty(request, gamedb_file_name));
	            gamedb_file_md5_lst.add(getParaElseEmpty(request, gamedb_file_md5));
	            gamedb_file_size_lst.add(getParaElseEmpty(request,  gamedb_file_size));
	            gamedb_file_time_lst.add(getParaElseEmpty(request, gamedb_file_time));
	            logdb_file_name_lst.add(getParaElseEmpty(request, logdb_file_name));
	            logdb_file_md5_lst.add(getParaElseEmpty(request, logdb_file_md5));
	            logdb_file_size_lst.add(getParaElseEmpty(request, logdb_file_size));
	            logdb_file_time_lst.add(getParaElseEmpty(request, logdb_file_time));
	            log_db_bak_stat_lst.add(getParaElseEmpty(request, log_db_bak_stat));
	            game_db_bak_stat_lst.add(getParaElseEmpty(request, game_db_bak_stat));
	            
	    		++gameserver_count;
	    	}
	    }
	    
	    System.out.println(area_type + ":有多少个游戏服备份信息:" + gameserver_count);
	    System.out.println("接收的游戏服备份信息有:" + gamedir_list);
	    System.out.println(gamedb_file_time_lst);
	    
	    for (int i = 0; i < gamedir_list.size(); ++i) {
	    	// 检查remote备份文件时间，取最新的备份文件(因为迁服后可能会有重复的游戏服目录)
	    	String gamedir = "";
	    	AppGamedbBakMsg existMsg = null;
	    	String gamedb_file_time = null;
	    	
	    	if (gamedb_file_time_lst.get(i) != null) {
	    		long oldFileTime = 0;
	            long newFileTime = 0;
	            gamedir = gamedir_list.get(i);

	            try {
	            	existMsg = appGamedbBakMsgService.fetch(Cnd.where("area_type", "=", area_type)
		            		.and("gamedir", "=", gamedir));
		            gamedb_file_time = existMsg.getGamedb_file_time();
	            } catch (Exception e) {
	            	System.out.println(gamedir + "新游戏服,没有查询到远程数据库备份信息");
	            }
	            
	            if (existMsg != null) {
	            	try {
	            		oldFileTime = DateUtil.parse(gamedb_file_time, "yyyy-MM-dd_HH:mm:ss").getTime();
	            	} catch (Exception e) {
	            		oldFileTime = 0;
	            	}
	            }
	            
	            try {
	            	newFileTime = DateUtil.parse(gamedb_file_time_lst.get(i), "yyyy-MM-dd_HH:mm:ss").getTime();
	            } catch (Exception e) {
	            	newFileTime = 0;
	            }

	            if (newFileTime < oldFileTime)
	                continue;
	            else
	                System.out.println("继续保存备份信息"); 
	    	}
	    	
	        // 是新的备份信息还是旧的备份信息？
	    	if (existMsg == null) {
	    		System.out.println("创建数据库备份记录");
	    		try {
	    			AppGamedbBakMsg msg = new AppGamedbBakMsg();
		    		msg.setArea_type(area_type);
		    		msg.setGamedir(gamedir);
		    		msg.setServer_id(Integer.parseInt(server_id_list.get(i)));
		    		msg.setCtcc_ip(local_ip);
		    		msg.setGamedb_file_name(gamedb_file_name_lst.get(i));
		    		msg.setGamedb_file_md5(gamedb_file_md5_lst.get(i));
		    		msg.setGamedb_file_size(gamedb_file_size_lst.get(i));
		    		msg.setGamedb_file_time(gamedb_file_time_lst.get(i));
		    		msg.setLogdb_file_name(logdb_file_name_lst.get(i));
		    		msg.setLogdb_file_md5(logdb_file_md5_lst.get(i));
		    		msg.setLogdb_file_size(logdb_file_size_lst.get(i));
		    		msg.setLogdb_file_time(logdb_file_time_lst.get(i));
		    		msg.setLog_db_bak_stat(log_db_bak_stat_lst.get(i));
		    		msg.setGame_db_bak_stat(game_db_bak_stat_lst.get(i));
		    		
		    		appGamedbBakMsgService._insert(msg);
	    		} catch (Exception e) {
	    			e.printStackTrace();
	    			System.out.println("出现异常，跳过：" + gamedir);
	    			continue;
	    		}
	    	} else {
	    		System.out.println("更新数据库备份信息");
	    		try {
	    			existMsg.setGamedir(gamedir);
	    			existMsg.setServer_id(Integer.parseInt(server_id_list.get(i)));
	    			existMsg.setCtcc_ip(local_ip);
	    			existMsg.setGamedb_file_name(gamedb_file_name_lst.get(i));
	    			existMsg.setGamedb_file_md5(gamedb_file_md5_lst.get(i));
	    			existMsg.setGamedb_file_size(gamedb_file_size_lst.get(i));
	    			existMsg.setGamedb_file_time(gamedb_file_time_lst.get(i));
	    			existMsg.setLogdb_file_name(logdb_file_name_lst.get(i));
	    			existMsg.setLogdb_file_md5(logdb_file_md5_lst.get(i));
	    			existMsg.setLogdb_file_size(logdb_file_size_lst.get(i));
	    			existMsg.setLogdb_file_time(logdb_file_time_lst.get(i));
	    			existMsg.setLog_db_bak_stat(log_db_bak_stat_lst.get(i));
	    			existMsg.setGame_db_bak_stat(game_db_bak_stat_lst.get(i));
	    			
	    			appGamedbBakMsgService._update(existMsg);
	    		} catch (Exception e) {
	    			e.printStackTrace();
	    			System.out.println("数据库插入或更新错误；或pickle文件不存在指定的key，可能是客户端提交脚本没有更新");
	    		}
	    	}
	    }
	
        return "Success";
    }
    
    private String getParaElseEmpty(HttpServletRequest request, String key) {
    	String v = request.getParameter(key);
    	return v == null ? "" : v;
    }
    
    @RequestMapping("/manualInfocenterBak")
    @ResponseBody
    @SystemLog(module = "数据库管理", oper = "中央服数据库本地备份")
    public Result<String> manualInfocenterBak(String ip){
    	Result<String> result = new Result<String>();
    	
    	Host host = hostService.fetch(Cnd.where("ctccIp", "=", ip));
    	
    	if (host == null) {
    		result.setCode(Result.FAIL);
    		result.setMsg("中央服不存在");
    	}
    	
    	String cmd = "/data/game_infocenter/cron/4.00/cron_backup_mysql.sh 2>&1";
    	
        try {
        	SSHExecResult sshResult = sshService.exec(host.getAvailablePublicIp(), host.getSshPort(), cmd);
        	result.setData(sshResult.getStdout());
        } catch (Exception e) {
        	e.printStackTrace();
        	result.setCode(Result.FAIL);
            result.setMsg(e.getMessage());
            return result;
        }
        
        result.setCode(Result.SUCCESS);
        result.setMsg("本地备份成功");

        return result;
    }

    @RequestMapping("/manualInfocenterBakRemote")
    @ResponseBody
    @SystemLog(module = "数据库管理", oper = "中央服数据库远程备份")
    public Result<String> manualInfocenterBakRemote(String ip){
    	Result<String> result = new Result<String>();
    	
    	try {
    		Host host = hostService.fetch(Cnd.where("ctccIp", "=", ip));
        	
        	if (host == null) {
        		result.setCode(Result.FAIL);
        		result.setMsg("中央服不存在");
        	}
        	
        	// 获取登录用户账户
    		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    		SysUser sysUser = (SysUser) request.getSession().getAttribute(Common.SESSION_LOGIN_USER_KEY);
        	        	
        	WebSocketSession wsSession = GlobalCache.wsSessionCacheMap.get(sysUser.getUserName());
        	if (wsSession == null) {
        		result.setCode(Result.FAIL);
        		result.setMsg("请重新刷新页面");
        	}
        	
        	// 异步执行
        	DbBakRemoteTask task = new DbBakRemoteTask(host.getAvailablePublicIp(),
        			host.getSshPort(), sshService, wsSession, Common.DB_INFOCENTER_BAK_REMOTE_PREFIX);
        	
        	ThreadUtil.execAsync(task);
        	
            result.setCode(Result.SUCCESS);
            result.setMsg("远程备份成功");
    	} catch (Exception e) {
    		e.printStackTrace();
        	result.setCode(Result.FAIL);
            result.setMsg(e.getMessage());
    	}

        return result;
    }

    @RequestMapping("/manualBak")
    @ResponseBody
    @SystemLog(module = "数据库管理", oper = "游戏库本地备份")
    public Result<String> manualBak(Integer serverId){
    	Result<String> result = new Result<String>();
    	
    	GameProcess gameProcess = gameProcessService.fetch(Cnd.where("serverId", "=", serverId));
    	
    	if (gameProcess == null) {
    		result.setCode(Result.FAIL);
    		result.setMsg("游戏服不存在");
    	}
    	
    	gameProcess = gameProcessService._fetchLinks(gameProcess, "host");
    	
    	String cmd = "/data/" + gameProcess.getDir() + "/cron.d/4.00/cron_backup_mysql.sh 2>&1";
    	
        try {
        	SSHExecResult sshResult = sshService.exec(gameProcess.getHost().getAvailablePublicIp(), gameProcess.getHost().getSshPort(), cmd);
        	result.setData(sshResult.getStdout());
        } catch (Exception e) {
        	e.printStackTrace();
        	result.setCode(Result.FAIL);
            result.setMsg(e.getMessage());
            return result;
        }
        
        result.setCode(Result.SUCCESS);
        result.setMsg("本地备份成功");

        return result;
    }
    
    @RequestMapping("/manualBakRemote")
    @ResponseBody
    @SystemLog(module = "数据库管理", oper = "游戏库远程备份")
    public Result<String> manualBakRemote(Integer serverId){
    	Result<String> result = new Result<String>();
    	
    	try {
        	GameProcess gameProcess = gameProcessService.fetch(Cnd.where("serverId", "=", serverId));
        	
        	if (gameProcess == null) {
        		result.setCode(Result.FAIL);
        		result.setMsg("游戏服不存在");
        	}
        	
        	// 获取登录用户账户
    		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    		SysUser sysUser = (SysUser) request.getSession().getAttribute(Common.SESSION_LOGIN_USER_KEY);
        	
        	gameProcess = gameProcessService._fetchLinks(gameProcess, "host");
        	
        	WebSocketSession wsSession = GlobalCache.wsSessionCacheMap.get(sysUser.getUserName());
        	if (wsSession == null) {
        		result.setCode(Result.FAIL);
        		result.setMsg("请重新刷新页面");
        	}
        	
        	// 异步执行
        	DbBakRemoteTask task = new DbBakRemoteTask(gameProcess.getHost().getAvailablePublicIp(),
        			gameProcess.getHost().getSshPort(), sshService, wsSession, Common.DB_BAK_REMOTE_PREFIX);
        	
        	ThreadUtil.execAsync(task);
        	
            result.setCode(Result.SUCCESS);
            result.setMsg("远程备份成功");
    	} catch (Exception e) {
    		e.printStackTrace();
        	result.setCode(Result.FAIL);
            result.setMsg(e.getMessage());
    	}

        return result;
    }
	
	@RequestMapping("/infocenter")
	public ModelAndView infocenter(Integer gameId) {
		// 总数
		int total = 0;

		// 正常
		int correct = 0;

		// 远程备份文件出错
		int warning = 0;

		// 没有远程备份文件
		int critical = 0;

		// 新装游戏服或没有提交脚本脚本提交失败
		int newGameserver = 0;
		
		List<Game> games = gameService.query(Cnd.where("state", "=", 1));

		if (gameId == null && games.isEmpty() == false) {
			gameId = games.get(0).getGameId();
		}
		
		List<InfocenterDbBakPO> poList = new ArrayList<>();
		
		if (gameId != null) {
			List<Host> infocenterList = hostService.query(Cnd.where("gameId", "=", gameId).and("role", "=", Common.HOST_ROLE_INFO_CENTER).and("state", "=", Common.HOST_STATE_ONLINE));
			
			if (infocenterList != null) {
				total = infocenterList.size();
				
				for (Host host : infocenterList) {
					AppInfocenterBakMsg localBakMsg = appInfocenterBakMsgService.fetch(Cnd.where("area_type", "=", "local")
							.and("ctcc_ip", "=", host.getAvailablePublicIp()));

					AppInfocenterBakMsg remoteBakMsg = appInfocenterBakMsgService.fetch(Cnd.where("area_type", "=", "remote")
							.and("ctcc_ip", "=", host.getAvailablePublicIp()));
					
					InfocenterDbBakPO po = new InfocenterDbBakPO();
					po.setIp(host.getAvailablePublicIp());
					poList.add(po);
					
					// ============================
					InfocenterDbBakItemPO itemPO = new InfocenterDbBakItemPO();
					itemPO.setArea("local");

					if (localBakMsg != null) {
						itemPO.setBakFileMd5(localBakMsg.getFile_md5());
						itemPO.setBakFileName(localBakMsg.getFile_name());
						itemPO.setBakFileSize(localBakMsg.getFile_size());
						itemPO.setBakTime(localBakMsg.getFile_time());
						itemPO.setState(localBakMsg.getDb_bak_stat());
					}

					po.getItems().add(itemPO);
					
					// ============================
					itemPO = new InfocenterDbBakItemPO();
					itemPO.setArea("remote");

					if (remoteBakMsg != null) {
						itemPO.setBakFileMd5(remoteBakMsg.getFile_md5());
						itemPO.setBakFileName(remoteBakMsg.getFile_name());
						itemPO.setBakFileSize(remoteBakMsg.getFile_size());
						itemPO.setBakTime(remoteBakMsg.getFile_time());
					}

					po.getItems().add(itemPO);
					
					// 比对local和remote的两个文件的md5
					String color = "";

					String localFileMd5 = null;
					if (localBakMsg != null) 
						localFileMd5 = localBakMsg.getFile_md5();

					String remoteFileMd5 = null;
					if (remoteBakMsg != null)
						remoteFileMd5 = remoteBakMsg.getFile_md5();

					if (localFileMd5 == null && remoteFileMd5 == null) {
						// 新装游戏服或没有提交脚本脚本提交失败
						color = "Blue";
						newGameserver++;
					}  else if (remoteFileMd5 == null) {
						// 没有远程备份文件
						color = "Red";
						critical++;
					} else if (localFileMd5 == null) {
						// 没有本地备份文件
						color = "Red";
						critical++;
					} else if (localFileMd5.equals(remoteFileMd5)) {
						// 备份成功
						color = "White";
						correct++;
					} else {
						// 远程备份文件出错
						color = "Yellow";
						warning++;
					}

					po.setColor(color);
				}
			}
		
		}
		
		Collections.sort(poList);
		
		return new ModelAndView("db/bakInfocenter")
				.addObject("total", total)
				.addObject("correct", correct)
				.addObject("warning", warning)
				.addObject("critical", critical)
				.addObject("newGameserver", newGameserver)
				.addObject("games", games)
				.addObject("gameId", gameId)
				.addObject("poList", poList);
	}

	@RequestMapping("/game")
	public ModelAndView game(Integer gameId) {
		// 总数
		int total = 0;

		// 正常
		int correct = 0;

		// 远程备份文件出错
		int warning = 0;

		// 没有远程备份文件
		int critical = 0;

		// 新装游戏服或没有提交脚本脚本提交失败
		int newGameserver = 0;

		List<Game> games = gameService.query(Cnd.where("state", "=", 1));

		if (gameId == null && games.isEmpty() == false) {
			gameId = games.get(0).getGameId();
		}
		
		List<GameDbBakPO> poList = new ArrayList<>();
		
		if (gameId != null) {
			List<GameProcess> gameProcessList = gameProcessService
					.query(Cnd.where("gameId", "=", gameId).and("state", "=", 1));
			if (gameProcessList != null) {
				total = gameProcessList.size();

				for (GameProcess gameProcess : gameProcessList) {
					gameProcess = gameProcessService._fetchLinks(gameProcess, "host");
					// 一个游戏服对应一个数据库备份
					// 分为游戏库和日志库
					// 一个库对应local和remote
					// 所以一行记录之中又分为4个子行
					AppGamedbBakMsg localBakMsg = appGamedbBakMsgService.fetch(Cnd.where("area_type", "=", "local")
							.and("gamedir", "=", gameProcess.getDir()).and("server_id", "=", gameProcess.getServerId()));

					AppGamedbBakMsg remoteBackMsg = appGamedbBakMsgService
							.fetch(Cnd.where("area_type", "=", "remote").and("gamedir", "=", gameProcess.getDir())
									.and("server_id", "=", gameProcess.getServerId()));

					GameDbBakPO po = new GameDbBakPO();
					po.setGameProcess(gameProcess);
					poList.add(po);

					// ============================
					GameDbBakItemPO itemPO = new GameDbBakItemPO();
					itemPO.setArea("local");
					itemPO.setDbName("游戏库");

					if (localBakMsg != null) {
						itemPO.setBakFileName(localBakMsg.getGamedb_file_name());
						itemPO.setBakFileMd5(localBakMsg.getGamedb_file_md5());
						itemPO.setBakFileSize(localBakMsg.getGamedb_file_size());
						itemPO.setBakTime(localBakMsg.getGamedb_file_time());
						itemPO.setGameDbState(localBakMsg.getGame_db_bak_stat());
						itemPO.setLogDbState(localBakMsg.getLog_db_bak_stat());
					}

					po.getItems().add(itemPO);

					// ============================
					itemPO = new GameDbBakItemPO();
					itemPO.setArea("remote");
					itemPO.setDbName("游戏库");

					if (remoteBackMsg != null) {
						itemPO.setBakFileName(remoteBackMsg.getGamedb_file_name());
						itemPO.setBakFileMd5(remoteBackMsg.getGamedb_file_md5());
						itemPO.setBakFileSize(remoteBackMsg.getGamedb_file_size());
						itemPO.setBakTime(remoteBackMsg.getGamedb_file_time());
					}

					po.getItems().add(itemPO);

					// =============================
					itemPO = new GameDbBakItemPO();
					itemPO.setArea("local");
					itemPO.setDbName("日志库");

					if (localBakMsg != null) {
						itemPO.setBakFileName(localBakMsg.getLogdb_file_name());
						itemPO.setBakFileMd5(localBakMsg.getLogdb_file_md5());
						itemPO.setBakFileSize(localBakMsg.getLogdb_file_size());
						itemPO.setBakTime(localBakMsg.getLogdb_file_time());
					}

					po.getItems().add(itemPO);

					// ==============================
					itemPO = new GameDbBakItemPO();
					itemPO.setArea("remote");
					itemPO.setDbName("日志库");

					if (remoteBackMsg != null) {
						itemPO.setBakFileName(remoteBackMsg.getLogdb_file_name());
						itemPO.setBakFileMd5(remoteBackMsg.getLogdb_file_md5());
						itemPO.setBakFileSize(remoteBackMsg.getLogdb_file_size());
						itemPO.setBakTime(remoteBackMsg.getLogdb_file_time());
					}

					po.getItems().add(itemPO);

					// ==================================

					// 比对local和remote的两个文件的md5
					String color = "";

					String localFileMd5 = null;
					if (localBakMsg != null) 
						localFileMd5 = localBakMsg.getGamedb_file_md5();

					String remoteFileMd5 = null;
					if (remoteBackMsg != null)
						remoteFileMd5 = remoteBackMsg.getGamedb_file_md5();

					if (localFileMd5 == null && remoteFileMd5 == null) {
						// 新装游戏服或没有提交脚本脚本提交失败
						color = "Blue";
						newGameserver++;
					} else if (remoteFileMd5 == null) {
						// 没有远程备份文件
						color = "Red";
						critical++;
					} else if (localFileMd5 == null) {
						// 没有本地备份文件
						color = "Red";
						critical++;
					} else if (localFileMd5.equals(remoteFileMd5)) {
						// 备份成功
						color = "White";
						correct++;
					} else {
						// 远程备份文件出错
						color = "Yellow";
						warning++;
					}

					po.setColor(color);
				}
			}

		}
		
		Collections.sort(poList);
		
		return new ModelAndView("db/bakGame")
				.addObject("total", total)
				.addObject("correct", correct)
				.addObject("warning", warning)
				.addObject("critical", critical)
				.addObject("newGameserver", newGameserver)
				.addObject("games", games)
				.addObject("gameId", gameId)
				.addObject("poList", poList);
		
	}
	
}
